<template>
  <div class="video-box" :id="randomId"></div>
</template>

<script lang="ts" setup>
import { onMounted, defineProps, ref, watch, onBeforeUpdate, onBeforeUnmount } from 'vue';
import Player from 'xgplayer';
import HlsPlayer from 'xgplayer-hls';
import HlsJsPlayer from 'xgplayer-hls.js'
import * as Api from '@/api/videoMonitor';

const props = defineProps<{
  deviceId: string,
  autoplay: boolean,
  isMobile: boolean
}>();
let player = ref<any>(null);
const url = ref('');
const getStream = async () => {
  const res = await Api.getStream({
    deviceId: props.deviceId,
    protocol: 'hls'
  });
  if (res) {
    url.value = res.url;
  }
}
const randomId = `video_${Date.now()}_${Math.ceil(Math.random() * 10000)}`;
onMounted(() => {
  if (!url.value && props.deviceId) {
    getStream();
  }
  // test
  // player.value = new Player({
  //   url: `//sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8`,
  //   id: randomId,
  //   height: '100%',
  //   width: '100%',
  //   autoplay: true,
  //   plugins: [HlsJsPlayer]
  // });
});
onBeforeUnmount(() => {
  if (player.value) {
    player.value.destroy()
  }
})
watch(url, () => {
  if (url.value) {
    player.value = new Player({
      url: url.value,
      id: randomId,
      height: '100%',
      width: '100%',
      autoplay: props.autoplay,
      plugins: [HlsJsPlayer]
    });
  }
})
</script>
<style lang="less" scoped>
.video-box {
  width: 100%;
  height: 100% !important;
}
</style>